package com.pdh.file.service;

import com.pdh.file.common.ErrorCode;
import com.pdh.file.entity.Result;
import com.pdh.file.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: 彭_德华
 * @Date: 2021-10-21 15:05
 */
@Service
public class UploadService {

    @Autowired
    private QiniuUtils qiniuUtils;

    /**
     * 两个存储路径可选
     * path1:存储在本机的指定位置
     * path2:存储在当前项目所在的目录下
     */
    private String path1 = "D:\\TempFile\\file\\";
    private String path2 = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\uploadFile\\";

    public Result uploadFileToLocal(MultipartFile[] files) {
        if (files.length == 0) {
            return Result.fail(ErrorCode.PARAMS_NULL.getCode(), ErrorCode.PARAMS_NULL.getMsg());
        }

        List<String> fileNameList = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileName = storeFile(file);
            fileNameList.add(fileName);
        }

        return Result.success(fileNameList);
    }

    public Result uploadFileToQiniu(MultipartFile[] files) {
        if (files.length == 0) {
            return Result.fail(ErrorCode.PARAMS_NULL.getCode(), ErrorCode.PARAMS_NULL.getMsg());
        }

        List<String> fileNameList = new ArrayList<>();
        for(MultipartFile file:files) {
            String fileName = uploadToQiniu(file);
            fileNameList.add(fileName);
        }

        return Result.success(fileNameList);
    }

    /**
     * 存储文件到本地
     * @param file
     * @return 文件名
     */
    private String storeFile(MultipartFile file){
        String originalFilename = file.getOriginalFilename();

        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); // +1是为了除去 . (点)
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;

        File elem = new File(path2 + fileName);
        if (!elem.getParentFile().exists()) {
            elem.getParentFile().mkdirs();
        }

        try {
            file.transferTo(elem);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return fileName;
    }

    /**
     * 存储文件到七牛云
     * @param file
     * @return 文件名
     */
    private String uploadToQiniu(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String fileName = System.currentTimeMillis() + "." + suffix;

        boolean flag = qiniuUtils.uploadSingleFile(file, fileName);
        if(flag){
            return fileName;
        }
        return null;
    }

}
